package nio.socket;

import org.junit.Test;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * @program JavaBase
 * @description:    阻塞式的网络通行
 * @author: zhanglu
 * @create: 2019-11-22 10:07:00
 *
 * 1、通道(Channel) 负责连接
 *  java.nio.channels.Channel 接口：
 *      - SelectableChannel
 *          - SocketChannel
 *          - ServerSocketChannel
 *          - DatagramChannel
 *
 *          - Pipe.SinkChannel
 *          - Pipe.SourceChannel
 *
 * 2、缓冲区(Buffer)    负责数据的存取
 * 3、选择器(Selector)  selectableChannel 的多路复用器。用于监控SelectableChannel的IO状况
 *
 *
 */
public class BlockingNio {



    /**
     * 客户端
     */
    @Test
    public void client() throws Exception {
        //获取通道
        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9898));

        //分配指定大小的缓冲区域
        ByteBuffer buf = ByteBuffer.allocate(1024);

        buf.put("我是客户端～".getBytes());

        buf.flip();

        //发送消息给服务端
        socketChannel.write(buf);

        socketChannel.close();
    }

    /**
     * 服务端
     */
    @Test
    public void server() throws Exception {
        //获取通道
        ServerSocketChannel serverChannel = ServerSocketChannel.open();

        //绑定连接
        serverChannel.bind(new InetSocketAddress(9898));

        //获取客户端连接的通道
        SocketChannel accept = serverChannel.accept();

        //接收客户端的消息

        ByteBuffer buf = ByteBuffer.allocate(1024);

        int len = -1;
        while ((len = accept.read(buf)) != -1){
            buf.flip();
            System.out.println(new String(buf.array(), 0, len));
        }
    }

    @Test
    public void client2() throws Exception {
        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 8989));

        ByteBuffer buf = ByteBuffer.allocate(1024);

        buf.put("我是客户端2～".getBytes());

        buf.flip();
        socketChannel.write(buf);
        buf.clear();

        socketChannel.shutdownOutput();

        int len = -1;
        while((len = socketChannel.read(buf)) != -1){
            buf.flip();
            System.out.println(new String(buf.array(), 0, len));
            buf.clear();
        }

        socketChannel.close();
    }

    @Test
    public void server02() throws Exception {
        ServerSocketChannel socketChannel = ServerSocketChannel.open();

        ServerSocketChannel channel = socketChannel.bind(new InetSocketAddress(8989));

        SocketChannel accept = channel.accept();

        ByteBuffer buf = ByteBuffer.allocate(1024);

        int len = -1;
        while((len = accept.read(buf)) != -1){
            buf.flip();
            System.out.println(new String(buf.array(), 0, len));
            buf.clear();
        }

        buf.put("你好客户端～".getBytes());
        buf.flip();
        accept.write(buf);

        accept.close();
        socketChannel.close();
    }

}
